package cn.humaohua.study.yanmo_design_pattern.ch13.v2;

import java.util.ArrayList;
import java.util.List;

/**
 * 计算器对象
 */
public class Calculator {

    private Command addCommand = null;
    private Command substractCommand = null;

    public void setAddCommand(Command addCommand) {
        this.addCommand = addCommand;
    }

    public void setSubstractCommand(Command substractCommand) {
        this.substractCommand = substractCommand;
    }

    public void addPressed() {
        this.addCommand.execute();
        // add undo
        this.undoCmds.add(this.addCommand);
    }

    public void substractPressed() {
        this.substractCommand.execute();
        // add undo
        this.undoCmds.add(this.substractCommand);
    }

    // 为计算器增加undo功能
    private List<Command> undoCmds = new ArrayList<Command>();

    public void undoPressed() {
        if (undoCmds.size() > 0) {
            Command cmd = this.undoCmds.remove(this.undoCmds.size() - 1);
            cmd.undo();
            this.reduCmds.add(cmd);
        } else {
            System.out.println("没有可撤销的命令");
        }
    }

    // 为计算器增加redo功能
    private List<Command> reduCmds = new ArrayList<Command>();

    public void redoPressed() {
        if (this.reduCmds.size() > 0) {
            Command cmd = this.reduCmds.remove(this.reduCmds.size() - 1);
            cmd.execute();
            this.undoCmds.add(cmd);
        } else {
            System.out.println("没有可恢复的命令");
        }
    }
}
